<?php

namespace App\Http\Controllers\Admin;

use App\Models\Article;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\AddArtRequest;

class ArticleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request  $request)
    {
        //dd($request->header('X-Requested-With'));
        if ($request->header('X-Requested-With') == 'XMLHttpRequest') {
            //是DataTables发起的ajax请求

            //这里没有对$request->get到的参数进行验证，还是验证靠谱一些，因为参数是走url的，容易出事

            //排序操作
            //用解构赋值接收php也支持 PHP7的语法
            //例子：
            //order[0][column]: 0
            //order[0][dir]: desc
            //对第$column列操作排序$dir='asc' / 'desc'
            ['column' => $column, 'dir' => $dir] = $request->get('order')[0];
            //获得排序的字段 例子:columns[1][data]: title
            $orderField = $request->get('columns')[$column]['data'];


            //记录开启位置
            $start = $request->get('start', 0);
            //获取记录数.
            //安全：最多取100个(以防破坏分子),参数是get跟过来的，有可能被坏人改掉
            $length = min(100, $request->get('length', 0));

            //搜索：开始时间 datemin: 2021-03-03
            $datemin = $request->get('datemin');
            //搜索：结束时间
            $datemax = $request->get('datemax');
            //搜索：文章标题关键字
            $title = $request->get('title');

            //新建一个查询对象
            $query = Article::query();
            //日期范围： 只有两个都设置了才有逻辑
            if (isset($datemin) && isset($datemax)) {
                //时间处理还不够严谨，1：判断datemax是否在datemin之后,最好让前端发送具体到秒的时间过来
                $datemin = date('Y-m-d H:i:s', strtotime($datemin . ' 00:00:00'));
                $datemax = date('Y-m-d H:i:s', strtotime($datemax . ' 00:00:00'));
                //dd(date('Y-m-d'));"2021-03-04"
                $query->whereBetween('created_at', [$datemin, $datemax]);
            }
            //搜索标题关键词,填了就有逻辑
            if (isset($title)) {
                $query->where('title', 'like', "%{$title}%");
            }

            //达成条件的记录总数
            $count = $query->count();
            //获取达成条件的数据
            $data = $query->orderBy($orderField, $dir)->offset($start)->limit($length)->get();
            /*
             * draw: 客户端调用服务器端次数标识
             * recordsTotal: 获取数据记录总条数
             * recordsFiltered: 数据过滤后的总数量
             * data: 获得的具体数据
             * 注意：recordsTotal和recordsFiltered都设置为记录的总条数
             * */
            $result = [
                'draw' => $request->get('draw'),
                'recordsTotal' => $count,
                'recordsFiltered' => $count,
                'data' => $data
            ];
            return $result;
        }
        //$data = Article::all();

        return view('admin.article.index', compact('data'));

    }

    /**
     * 添加文章:显示
     */
    public function create()
    {
        return view('admin.article.create');
    }

    /**
     * 添加文章： 处理
     */
    public function store(AddArtRequest $request)
    {
        //独立表单验证AddArtRequest
        //不上传也要给一张默认图片
        // 封面图片

        $pic = config('up.pic');//默认图片路径(用户没传就用这张)
//        if ($request->hasFile('pic')) {
//            //上传图片到cfg_article_pic
//            $new_file_name = $request->file('pic')->store('', 'cfg_article_pic'); //这个cfg_article_pic是filesystems.php里头那个配置名
//            if (is_string($new_file_name)) {
//                //保存成功
//                $pic = '/uploads/article/' . $new_file_name; //完整路径
//            }
//        }
        //准备入库的数据$post
        $post = $request->except('_token', 'file');
        $post['pic'] = $pic;
        //入库
        Article::create($post);
        return redirect(route("admin.article.index"));
    }

    //文件上传
    public function upfile(Request $request) {
        $pic = config('up.pic');
        if ($request->hasFile('file')) {
            //上传图片到cfg_article_pic
            $new_file_name = $request->file('file')->store('', 'cfg_article_pic'); //这个cfg_article_pic是filesystems.php里头那个配置名
            if (is_string($new_file_name)) {
                //保存成功
                $pic = '/uploads/article/' . $new_file_name; //完整路径
            }
        }
        return ['status' => 0, 'url' => $pic];
        //成功return案例
        //status: 0
        //url: "/uplodas/articlemMqi9b6XPk1jlckVKpPUs4PwUKbIDC4Wycgqabco.jpeg"
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Article  $article
     * @return \Illuminate\Http\Response
     */
    public function show(Article $article)
    {
        //
    }

    /**
     * 文章修改 显示
     */
    public function edit(Article $article)
    {
        return view('admin.article.edit', compact('article'));
    }

    /**
     * 文章修改 处理
     */
    public function update(Request $request, Article $article)
    {
        $putData = $request->except(['action', 'created_at', 'updated_at', 'deleted_at', 'id', 'opts']);
        $article->update($putData);
        return ['status' => 0, 'url'=>route('admin.article.index')];
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Article  $article
     * @return \Illuminate\Http\Response
     */
    public function destroy(Article $article)
    {
        //软删除
        $article->delete();

        return ['id' => 111];
    }
}
